$(document).ready(function() {
	refreshMyTable(true);
	getCustomGroupsforUser();
	// alert("DD");
//	alert($(".update").style.visibility);
	hideElements('updateUser',updateWhat);
	hideElements('insertUser',insertWhat);
	hideElements('deleteUser',deleteWhat);
	
//	alert($("#chkall").parent().children().remove());
});

function hideElements(withElement,what)
{	
//	$('.deleteUser').addClass('disabled');
//	alert(withElement+" "+what);
	 var elements = document.getElementsByClassName(withElement);
if(what=='true')
	 for (var i = 0; i < elements.length; i++) {
//		    elements[i].style.cursor='not-allowed';
//		    elements[i].addClass('disabled');
//		 elements[i].value="Disabled";
	     elements[i].disabled='true';
	  
	 }
}
function getCustomGroupsforUser() {

	$.ajax({
		url : host + '/easyskool/rest/idModService/getCustomGroups',
		type : 'POST',
		data : '{}',
		dataType : 'json',
		async : true,
		contentType : "application/json; charset=utf-8",
		success : function(data, testStatus, response) {
			var jsondata = JSON.parse(response.responseText);
			var toAppend = "";
			var hiddenCols = [ "" ];
			$.each(jsondata, function(i, item) {
				$("#customGroups").append(
						'<option value="' + jsondata[i].agCode + '">'
								+ jsondata[i].agName + '</option>');
				$("#uGroupCode").append(
						'<option value="' + jsondata[i].agCode + '">'
								+ jsondata[i].agName + '</option>');
				
			});
		},
		error : function(data, testStatus, response) {
			alert("An error ocured");
		}

	});
}
function insertUser() {
	alert(document.getElementById("customGroups").value);

	if($('#addUserForm').valid()) {
		formData = ($('#addUserForm').serializeArray());
		alert(converter(formData));
		$.ajax({
		    url : host+'/easyskool/rest/idModService/insertUser',
			type : 'POST',
			async: false,
			data :converter(formData),
			dataType : 'json',
			contentType : "application/json; charset=utf-8",
			success : function(data,testStatus,jqXHR) {
				var json = jQuery.parseJSON(jqXHR.responseText);
					 alert(json.responseMessage);
//					 refreshMyTable(true);
			},
		error : function(data,testStatus,jqXHR) {
			 alert("Error saving record");
		}
	    });
    	}
 
}
function updateUser() {

	if($('#updateForm').valid()) {
		formData = ($('#updateForm').serializeArray());
		alert(converter(formData));
		$.ajax({
		    url : host+'/easyskool/rest/idModService/updateUser',
			type : 'POST',
			async: false,
			data :converter(formData),
			dataType : 'json',
			contentType : "application/json; charset=utf-8",
			success : function(data,testStatus,jqXHR) {
				var json = jQuery.parseJSON(jqXHR.responseText);
					 alert(json.responseMessage);
					 refreshMyTable(true);
			},
		error : function(data,testStatus,jqXHR) {
			 alert("Error saving record");
		}
	    });
    	}
 
}
function createTableAgain()
{
	var jsondata=tableData;
	var toAppend = "";
	var hiddenCols = ["uaCode" ];
	allCustomGroups=jsondata;
	$("#mytable").remove();
	createMyTable();
	
	$("#mytable").append("<tbody id='tbodyId'>");
	$.each(jsondata, function(i, item) {
		toAppend = "";
		toAppend = startTableRow(toAppend, i);
		toAppend = addCheckboxToTableRow(toAppend, 'checkboxselect', i+"c");
		toAppend = jsonItemToString(toAppend, item, hiddenCols);
		toAppend = addButtonWithModalToTable(toAppend, 'Update', 'btn btn-info btn-xs updateUser', 'update', 'myUpdateModal',jsondata[i].uaCode);
		toAppend = addButtonWithoutModalToTable(toAppend, 'Delete', 'btn btn-danger btn-xs deleteUser', 'remove'+i);
		toAppend = endTableRow(toAppend);
		$("#mytable").append(toAppend);
	});
	$("#mytable").append("</tbody>");
	refreshTableSorter();
}
	var tableData;
	function refreshMyTable(asyncVal)
	{ //	alert("REFRESHING");
		$("#loading").append("Loading.......");
		$.ajax({
			url:host+'/easyskool/rest/idModService/getUsers',
			type:'POST',
			data: '{}',
			dataType: 'json',
			async: asyncVal,
			contentType: "application/json; charset=utf-8",
			success:function (data,testStatus,response) {
				var jsondata =JSON.parse(response.responseText);
				tableData=jsondata;
				var toAppend = "";
				var hiddenCols = ["uaCode" ];
				allCustomGroups=jsondata;
				$("#mytable").remove();
				createMyTable();
				
				$("#mytable").append("<tbody id='tbodyId'>");
				$.each(jsondata, function(i, item) {
					toAppend = "";
					toAppend = startTableRow(toAppend, i);
					toAppend = addCheckboxToTableRow(toAppend, 'checkboxselect', i+"c");
					toAppend = jsonItemToString(toAppend, item, hiddenCols);
					toAppend = addButtonWithModalToTable(toAppend, 'Update', 'btn btn-info btn-xs updateUser', 'update', 'myUpdateModal',jsondata[i].uaCode);
					toAppend = addButtonWithoutModalToTable(toAppend, 'Delete', 'btn btn-danger btn-xs deleteUser', 'remove'+i);
					toAppend = endTableRow(toAppend);
					$("#mytable").append(toAppend);
				});
				$("#mytable").append("</tbody>");
				refreshTableSorter();
				$("#loading").remove();
			},
			error:function (data,testStatus,response) {
			alert("Error fetching data");
			}
		});
		
		
		attachClickEventToUpdateButton();
//		attachClickEventToDeleteButton();
//		attachClickEventToSelectAllCheckBox();
	}

	function addButtonWithModalToTable(toAppend, buttonValue, buttonClass,
			buttonId, modalName,code) {
		toAppend = toAppend + "<td><input type='button' value='" + buttonValue
				+ "' class='" + buttonClass + "' id='" + buttonId
				+ "' data-toggle='modal' data-target='#" + modalName + "' name='"+code+"'  /></td>";
		return toAppend;
	}
	function attachClickEventToUpdateButton() {
		$('#mytable').on('click', '#update', function(){
		var currRowId=	$(this).closest('tr').attr('id');;
		//document.getElementById(currRowId).cells[1].innerHTML
		document.getElementById("uName").value=$(".uaName")[currRowId].innerHTML	;
		document.getElementById("uemail").value=$(".uaEmail")[currRowId].innerHTML	;
		document.getElementById("ucode").value=$(".uaCode")[currRowId].innerHTML	;
		var ddl = document.getElementById('uGroupCode');
		var opts = ddl.options.length;
		for (var i=0; i<opts; i++){
		    if (ddl.options[i].value == $(".uaGroup")[currRowId].innerHTML){
		        ddl.options[i].selected = true;
		        break;
		    }
		}
//		alert($(".update")[1]);
	   });
	}

	function jsonItemToString(toAppend, item, hiddenCols) {

		$.each(item, function(key, value) {
			var found = $.inArray(key, hiddenCols) > -1;
			if (found == false) {
				toAppend = toAppend + "<td class='" + key + "'>" + value + "</td>";
			} else {
				toAppend = toAppend + "<td class='" + key + "' hidden='true'>"
						+ value + "</td>";
			}

			// alert(key + "," + value);
		});

		return toAppend;
	}

	function addButtonWithoutModalToTable(toAppend, buttonValue, buttonClass,
			buttonId) {
		toAppend = toAppend + "<td><input type='button' value='" + buttonValue
				+ "' class='" + buttonClass + "' id='" + buttonId + "' onclick='deleteUserJs(this.id);' /></td>";
		return toAppend;
	}
	
 

	function deleteMultipleUserJs() {
	    	$("#myConfirmModal").modal('show');
	    	
	    	$('#confirmDelete').click(function() {
	    		
	    		$("#myConfirmModal").modal('hide');
//	    		alert(document.getElementsByName("checkboxselect").item(5).checked );
	    		var chk=document.getElementsByName("checkboxselect");
	    		var ids="";
	    		var idsofParent=[];
	    		var flag=0;
	    		for(var i=0;i<chk.length;i++)
	    			{
	    			var idOfParent=$('#'+chk.item(i).id).parent().parent().attr('id');
	    			if(chk.item(i).checked)
	    			{ids=ids+','+$('#'+idOfParent).find('.uaCode').text();
	    			idsofParent.push(idOfParent);
	    			flag=1;
	    			}
	    			}
	    		if(flag!=1)
	    			{
	    			alert("Please select an entry to delete");
	    			flag=0;
	    			return;
	    			}
	           	$.ajax({
	           		url : host+'/easyskool/rest/idModService/deleteMultipleUser',
	       			type : 'POST',
	       			data : '{"uCode":"'+ids+'"}',
	       			dataType : 'json',
	       			async:false,
	       			contentType : "application/json; charset=utf-8",
	       			success : function(data,testStatus,response) {
	       				var json = jQuery.parseJSON(response.responseText);
	       				if(json.responseCode == "success"){
//	       					refreshMyTable(true);
	       					refreshMyTable(false);
//	       					for(var i=0;i<idsofParent.length;i++)
//	       						{
////	       						var uaCodeOfId=$('#'+idsofParent[i]).find('.uaCode').text();
////	       						tableData.splice(idsofParent[i], 1);
////	       						createTableAgain();
//	       						var element = document.getElementById(idsofParent[i]);
//	    	       				document.getElementById(idsofParent[i]).className += " remove-me";
//	    	       				element.parentNode.removeChild(element);
//	    	       			
//	       						} $('#mytable').trigger('update');
	       				
	       				} else	{
	    					alert(json.responseMessage);
	    					var notDeletedids=json.responseMessage.split(",");
	    					for(var i=0;i<idsofParent.length;i++)
       						{
	    						var uaCode=$('#'+idsofParent[i]).find('.uaCode').text();
	    						  
	    						  if(jQuery.inArray(uaCode, notDeletedids )==-1)
	    							 {	var uaCodeOfId=$('#'+idsofParent[i]).find('.uaCode').text();
	    								var element = document.getElementById(idsofParent[i]);
	    	    	       				document.getElementById(idsofParent[i]).className += " remove-me";
	    	    	       				element.parentNode.removeChild(element);
	    	    	       			
	    	       						} $('#mytable').trigger('update');
       						}
	       				}
	       			}
	           	});
	           	
	           	idsofParent=[];
	        });
	    	
	    	$('#cancelDelete').click(function() {
	    		$("#myConfirmModal").modal('hide');
	    	
	    	});
	    	return;
	}
	function deleteUserJs(id) {
	    	var curRowId = $('#'+id).parent().parent().closest('tr');
	    	$("#myConfirmModal").modal('show');
	    	
	    	$('#confirmDelete').click(function() {
	    		
	    		$("#myConfirmModal").modal('hide');
	           	$.ajax({
	           		url : host+'/easyskool/rest/idModService/deleteUser',
	       			type : 'POST',
	       			data : '{"uCode":"'+curRowId.children('td.uaCode').text()+'"}',
	       			dataType : 'json',
	       			async:false,
	       			contentType : "application/json; charset=utf-8",
	       			success : function(data,testStatus,response) {
	       				var json = jQuery.parseJSON(response.responseText);
	       				if(json.responseCode == "success"){
	       				var element = document.getElementById(curRowId.attr('id'));
	       				document.getElementById(curRowId.attr('id')).className += " remove-me";
	       				element.parentNode.removeChild(element);
	       			 $('#mytable').trigger('update');
	       				} else	{
	    					alert(json.responseMessage);
	       				}
	       			}
	           	});
//	           	
	            
	        });
	    	
	    	$('#cancelDelete').click(function() {
	    		$("#myConfirmModal").modal('hide');
	    	
	    	});
	    	
	}
	function createTableHeader(toAppend, theaders, createSelectAllCheckboxFlag) {
		
		toAppend += "<thead>";
		toAppend += 	"<tr>";
		
		if(createSelectAllCheckboxFlag) {		
			toAppend +=		"<th><input id='chkall'  onclick='selectAll(); 'name='chkall' type='checkbox' ></th>";
		}
		
		for ( var i = 0; i < theaders.length; i++) {
//			if(theaders[i][1]) {
//				toAppend += 		"<th hidden='true'>" + theaders[i][0] + "</th>";
//			} else {
				toAppend += 		"<th>" + theaders[i] + "</th>";
//			}
		}
		
		toAppend += 	"</tr>";
		toAppend += "</thead>";

		return toAppend;
	}
	function createMyTable() {
		var toAppend = "";
		//var tableId = "mytable";
		var theaders = ["Phone	","Creater",
		                "Name","E-Mail","Group","Update","Delete"
		               ];
		toAppend +=	"<table class='table form-fields table-striped tablesorter' id='mytable'>";
		toAppend = createTableHeader(toAppend, theaders, true);
		toAppend = attachPaginationBarToTable(toAppend);
		toAppend += "</table>";
		
		$("#tableDiv").append(toAppend);
	}

	function selectAll() {
		if(document.getElementById("chkall").checked)
			{//alert('if;');
			$('input[name=checkboxselect]').prop('checked', true);}
		 else {
				$('input[name=checkboxselect]').prop('checked', false);
			}
	}
	
  /*
  * Refresh Table Sorter Widget after table content is changed
  * 
  * return <void>
  */
 function refreshTableSorter() {
 	
 	$(function() {

			$.extend($.tablesorter.themes.bootstrap, {
				// these classes are added to the table. To see other table classes available,
				// look here: http://twitter.github.com/bootstrap/base-css.html#tables
				table      : 'table table-bordered',
				caption    : 'caption',
				header     : 'bootstrap-header', // give the header a gradient background
				footerRow  : '',
				footerCells: '',
				icons      : '', // add "icon-white" to make them white; this icon class is added to the <i> in the header
				sortNone   : 'bootstrap-icon-unsorted',
				sortAsc    : 'icon-chevron-up glyphicon glyphicon-chevron-up',     // includes classes for Bootstrap v2 & v3
				sortDesc   : 'icon-chevron-down glyphicon glyphicon-chevron-down', // includes classes for Bootstrap v2 & v3
				active     : '', // applied when column is sorted
				hover      : '', // use custom css here - bootstrap class may not override it
				filterRow  : '', // filter row class
				even       : '', // odd row zebra striping
				odd        : ''  // even row zebra striping
			});

			// call the tablesorter plugin and apply the uitheme widget
			$("#mytable").tablesorter({
				// this will apply the bootstrap theme if "uitheme" widget is included
				// the widgetOptions.uitheme is no longer required to be set
				theme : "bootstrap",

				  headers: {
				        // set "sorter : false" (no quotes) to disable the column
					  0: {
				            sorter: "false",
				             filter: false
				        },
				        6: {
				            sorter: "false",
				             filter: false
				        },
				        7: {
				            sorter: "false",
				             filter: false
				        },
				        

				    },
				widthFixed: true,
//				showProcessing: false,
				headerTemplate : '{content} {icon}', // new in v2.7. Needed to add the bootstrap icon!

				// widget code contained in the jquery.tablesorter.widgets.js file
				// use the zebra stripe widget if you plan on hiding any rows (filter widget)
				widgets : [ "uitheme", "filter", "zebra" ],

				widgetOptions : {
					// using the default zebra striping class name, so it actually isn't included in the theme variable above
					// this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
					zebra : ["even", "odd"],

					// reset filters button
					filter_reset : ".reset"

					// set the uitheme widget to use the bootstrap theme class names
					// this is no longer required, if theme is set
					// ,uitheme : "bootstrap"

				}
			})
			.tablesorterPager({

				// target the pager markup - see the HTML block below
				container: $(".ts-pager"),

				// target the pager page select dropdown - choose a page
				cssGoto  : ".pagenum",

				// remove rows from the table to speed up the sort of large tables.
				// setting this to false, only h	ides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
//				removeRows: true,

				// output string - default is '{page}/{totalPages}';
				// possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
				output: '{startRow} - {endRow} / {filteredRows} ({totalRows})'

			});

		});
		
		$(function(){

				// filter button demo code
				$('button.filter').click(function(){
					var col = $(this).data('column'),
						txt = $(this).data('filter');
					$('#mytable').find('.tablesorter-filter').val('').eq(col).val(txt);
					$('#mytable').trigger('search', false);
					return false;
				});

				// toggle zebra widget
				$('button.zebra').click(function(){
					var t = $(this).hasClass('btn-success');

					$('#mytable')
						.toggleClass('table-striped')[0]
						.config.widgets = (t) ? ["uitheme", "filter"] : ["uitheme", "filter", "zebra"];
					$(this)
						.toggleClass('btn-danger btn-success')
						.find('i')
						.toggleClass('icon-ok icon-remove glyphicon-ok glyphicon-remove').end()
						.find('span')
						.text(t ? 'disabled' : 'enabled');
					$('#mytable').trigger('refreshWidgets', [false]);
					return false;
				});
			});
 }

